﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace WebApi
{
    public class CorsAttribute : ActionFilterAttribute
    {
       public string[]  AllowOrigins { get; private set; }
         public CorsAttribute(params string[] allowOrigins)
       {
           this.AllowOrigins = (allowOrigins ?? new string[0]).ToArray();
       }
        private const string Origin = "Origin";

        /// <summary>
        /// Access-Control-Allow-Origin是HTML5中定义的一种服务器端返回Response header，用来解决资源（比如字体）的跨域权限问题。
        /// </summary>
        private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";

        /// <summary>
        /// 该方法允许api支持跨域调用
        /// </summary>
        /// <param name="actionExecutedContext"> 初始化 System.Web.Http.Filters.HttpActionExecutedContext 类的新实例。</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
           
            actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, AllowOrigins.FirstOrDefault());
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST,OPTIONS,DELETE,PUT");
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
 
        }
    }

}
